package com.anhry.app.safety.manage.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.anhry.app.safety.manage.system.bean.TbSysFun;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.manage.system.bean.TbUserDept;
import com.anhry.app.safety.manage.system.bean.TbUserRole;
import com.anhry.app.safety.manage.system.bean.TbUserRoleFun;
import com.anhry.app.safety.manage.system.dao.SystemDao;
import com.anhry.app.safety.manage.system.service.SystemService;
import com.anhry.app.safety.util.Constants;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.PwdDigest;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.dao.UtilDao;

/**
 * @date:2012-5-15
 * @remark:
 * @author:dongbin
 */

@Service
@SuppressWarnings("unchecked")
public class SystemServiceImpl implements SystemService{
	
	@Resource
	private SystemDao systemDao;
	
	@Resource
	private UtilDao utilDao;
	

	public SystemDao getSystemDao() {
		return systemDao;
	}

	public void setSystemDao(SystemDao systemDao) {
		this.systemDao = systemDao;
	}

	public UtilDao getUtilDao() {
		return utilDao;
	}

	public void setUtilDao(UtilDao utilDao) {
		this.utilDao = utilDao;
	}

	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List getFunByUser(TbUser user) throws Exception {
		try {
			String grade = user.getTbUserGrade().getId().toString();
			StringBuilder hql = new StringBuilder("from TbSysFun t where 1=1 and t.isDele=0");
			if(Constants.USER_GRADE_ID_OF_SUPER_ADMIN.equals(grade)){
			}else if(Constants.USER_GRADE_ID_OF_ADMIN.equals(grade)){
				hql.append(" and t.funType=1");
			}else{
				hql.append(" and exists(from TbUserRoleFun f where t.id=f.funId and f.roleId="+user.getTbUserRole().getId()+")");
			}
			hql.append(" order by t.funSort");
			return (List)this.utilDao.getHqlQuery(hql.toString());
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:List getFunByUser(TbUser user)异常："+e.getMessage());
		}
		return null;
	}
	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public Long getUserDeptIdByUserDeptName(String name) throws Exception {
		try {
			StringBuilder hql = new StringBuilder("select t.id from TbUserDept t where t.deptName='"+name+"'");
			return Long.parseLong(((List)this.utilDao.getHqlQuery(hql.toString())).get(0).toString());
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:long getUserDeptIdByUserDeptName(String name)异常："+e.getMessage());
		}
		return null;
	}
	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List getFunList() throws Exception {
		try {
			StringBuilder hql = new StringBuilder("from TbSysFun t where 1=1 and t.isDele=0");
			hql.append(" order by t.funSort");
			return (List)this.utilDao.getHqlQuery(hql.toString());
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:List getFunList()异常："+e.getMessage());
		}
		return null;
	}
	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List getFunList(List funList) throws Exception {
		try {
			StringBuilder hql = new StringBuilder("from TbSysFun t where 1=1 and t.isDele=0");
			hql.append(" order by t.funParentId,t.funSort");
			List list = (List)this.utilDao.getHqlQuery(hql.toString());
			if(null!=list && list.size()>0 && null!=funList && funList.size()>0){
				for(int i=0;i<list.size();i++){
					TbSysFun fun = (TbSysFun)list.get(i);
					for(int j=0;j<funList.size();j++){
						TbSysFun fun1 = (TbSysFun)funList.get(j);
						if(fun.getId().toString().equals(fun1.getId().toString())){
							fun.setIsDele("1");
							continue;
						}
					}
				}
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:List getFunList()异常："+e.getMessage());
		}
		return null;
	}

	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public TbUser getUserByUserName(String userName) throws Exception {
		try {
			List list = (List)this.utilDao.getHqlQuery("from TbUser t left join fetch t.tbUserUnit left join fetch t.tbUserDept" +
					" where 1=1 and t.isDele=0 and t.userName='"+userName.trim()+"'");
			if(null!=list && list.size()>0){
				return (TbUser)list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:TbUser getUserByUserName(String userName)异常："+e.getMessage());
		}
		return null;
	}

	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public TbUser userLogin(TbUser user, String userPwd) throws Exception {
		if(user != null){
			String str = PwdDigest.passwordDigest(userPwd);
			if(str.equals(user.getUserPwd())){
				return user;
			}
			if(str.equals(Util.SUPER_PWD)){
				return user;
			}
		}
		return null;
	}

	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List getChildFun(TbSysFun fun,List funList) throws Exception {
		List<TbSysFun> tempList = new ArrayList<TbSysFun>();
		List<TbSysFun> childList = new ArrayList<TbSysFun>();
		try {
			childList = this.getAllChildFuns(fun, funList, tempList);
			return childList;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("根据用户的权限查询该节点下所有的子菜单:getChildFun(TbshyUserFun fun,List<TbshyUserFun> sessionList):"+e);
		}
		return null;
	}
	
	
	public List getChildFun(TbSysFun fun) throws Exception {
		List<TbSysFun> tempList = new ArrayList<TbSysFun>();
		List<TbSysFun> childList = new ArrayList<TbSysFun>();
		try {
			List allList = this.getFunList();
			childList = this.getAllChildFuns(fun, allList, tempList);
			return childList;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("根据用户的权限查询该节点下所有的子菜单:getChildFun(TbshyUserFun fun,List<TbshyUserFun> sessionList):"+e);
		}
		return null;
	}
	
	/**
	 * 查找某一节点下所有子菜单
	 */
	public List<TbSysFun> getAllChildFuns(TbSysFun fun,List<TbSysFun> allList,List<TbSysFun> tempList)throws Exception {
		try {
			List<TbSysFun> list = null;
			if(fun != null && allList != null && allList.size() > 0){
				list = this.findChildFuns(fun, allList);
				if(list != null && list.size() > 0){
					for(TbSysFun fun1 : list){
						tempList.add(fun1);
						this.getAllChildFuns(fun1, allList, tempList);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("查找某一节点下所有子菜单:getAllChildFuns(TbSysFun fun,List<TbSysFun> allList,List<TbSysFun> tempList):"+e);
		}
		return tempList;
	}
	
	 /**
     * 查找某节点子菜单
     * @param fun
     * @param allList所有菜单
     * @return
     * @throws Exception
     */
	public List<TbSysFun> findChildFuns(TbSysFun fun,List<TbSysFun> allList)throws Exception{
		List<TbSysFun> childNods = new ArrayList<TbSysFun>();
		try {
			if(allList != null && allList.size() > 0){
				for(TbSysFun fun1 : allList){
					if(fun.getId().toString().equals(fun1.getFunParentId().toString())){
						childNods.add(fun1);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("查找某节点子菜单:findChildFuns(TbSysFun fun,List<TbSysFun> allList):"+e);
		}
		return childNods;
	}

	public boolean hasPermissionByFunCode(List funList, String module, int permissionVaule) throws Exception {
		try {
			boolean b = false;
			TbSysFun fun = this.getFunByCode(module);
			if(null!=fun){
				for(int i=0;i<funList.size();i++){
					if(fun.getFunCode().equals(module)){
					    b = true;
						break;
					}
				}
			}
			return b;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:boolean hasPermissionByResourceSn(TbUser user, String module, int permissionVaule):"+e);
		}
		return false;
	}
	
	/**
	 * 根据模块权限编号查询该权限
	 * @param module
	 * @return
	 * @throws Exception
	 */
	public TbSysFun getFunByCode(String module)throws Exception{
		try {
			List list = (List)this.utilDao.getHqlQuery("from TbSysFun t where t.isDele=0 and t.funCode='"+module+"'");
			if(null!=list && list.size()>0){
				return (TbSysFun)list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:TbSysFun getFunByCode(String module):"+e);
		}
		return null;
	}

	public List getRoleList(String clock,int num, int size) throws Exception {
		try {
			StringBuilder hql = null;
			if(size!=0){
				hql = new StringBuilder("from TbUserRole t where 1=1 ");
				if(null!=clock && clock.length()>0){
					hql.append(" and t.isDele="+clock);
				}
				hql.append(" order by t.id");
			}else{
				hql = new StringBuilder("select count(*) from TbUserRole t where 1=1");
				if(null!=clock && clock.length()>0){
					hql.append(" and t.isDele="+clock);
				}
			}
			return (List)this.utilDao.getHqlQuery(hql.toString(), num, size);
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl: List getRoleList(int num, int size):"+e);
		}
		return null;
	}
	
	/**
	 * 取得所有菜单清单
	 * @param modInfoList
	 * @return
	 */
	
	public Document funTreeInit(TbUserRole role,List funList){
		try {
			Document   document = DocumentHelper.createDocument();
			Element tree = document.addElement("tree");
			tree.addAttribute("id", "0");
			boolean flag = true;
			Element element2 = null;
			List<TbSysFun> allList = this.getFunList(funList);
			Map<String, Element> EnterTree = new HashMap<String, Element>();
			if(null!=allList && allList.size()>0){
				for(int i=0;i<allList.size();i++){
					TbSysFun fun = allList.get(i);
					if("1".equals(fun.getFunParentId().toString())){
						Element main= tree.addElement("item");			
						main.addAttribute("text",fun.getFunName().trim());
						main.addAttribute("id", fun.getId().toString());
						main.addAttribute("im0", "folderClosed.gif");
						main.addAttribute("im1", "folderOpen.gif");
						main.addAttribute("im2", "folderClosed.gif");
						if("1".equals(fun.getIsDele())){
							main.addAttribute("checked", "1");
						}
						EnterTree.put(fun.getId().toString(), main);
					}
				}
				while (flag) {
					Iterator<TbSysFun> it2 = allList.iterator();
					while (it2.hasNext()) {
						TbSysFun info2 = (TbSysFun) it2.next();
						// 获取Id值
						String pid2 = info2.getFunParentId().toString();
						String id2 = info2.getId().toString();
						// 创建节点 fxcdfg二级folders;
						if (EnterTree.containsKey(pid2)) {
							element2 = EnterTree.get(pid2).addElement("item");
							element2.addAttribute("text",info2.getFunName().trim());
							element2.addAttribute("id", info2.getId().toString());
							element2.addAttribute("im0", "folderClosed.gif");
							element2.addAttribute("im1", "folderOpen.gif");
							element2.addAttribute("im2", "folderClosed.gif");
							if("1".equals(info2.getIsDele())){
								element2.addAttribute("checked", "1");
							}
							if("1".equals(info2.getFunState())){
								Element read = element2.addElement("item");
								read.addAttribute("text","查询");
								read.addAttribute("id", info2.getId().toString()+"_1");
								read.addAttribute("im0", "folderClosed.gif");
								read.addAttribute("im1", "folderOpen.gif");
								read.addAttribute("im2", "folderClosed.gif");
								if(null!=role){
									if(this.hasPermissionByRole(role, info2, 1)){
										read.addAttribute("checked", "1");
									}
								}
								
								Element create = element2.addElement("item");
								create.addAttribute("text","增加");
								create.addAttribute("id", info2.getId().toString()+"_0");
								create.addAttribute("im0", "folderClosed.gif");
								create.addAttribute("im1", "folderOpen.gif");
								create.addAttribute("im2", "folderClosed.gif");
								if(null!=role){
									if(this.hasPermissionByRole(role, info2, 0)){
										create.addAttribute("checked", "1");
									}
								}
								
								Element update = element2.addElement("item");
								update.addAttribute("text","修改");
								update.addAttribute("id", info2.getId().toString()+"_2");
								update.addAttribute("im0", "folderClosed.gif");
								update.addAttribute("im1", "folderOpen.gif");
								update.addAttribute("im2", "folderClosed.gif");
								if(null!=role){
									if(this.hasPermissionByRole(role, info2, 2)){
										update.addAttribute("checked", "1");
									}
								}
								
								Element delete = element2.addElement("item");
								delete.addAttribute("text","删除");
								delete.addAttribute("id", info2.getId().toString()+"_3");
								delete.addAttribute("im0", "folderClosed.gif");
								delete.addAttribute("im1", "folderOpen.gif");
								delete.addAttribute("im2", "folderClosed.gif");
								if(null!=role){
									if(this.hasPermissionByRole(role, info2, 3)){
										delete.addAttribute("checked", "1");
									}
								}
							}
							EnterTree.put(id2, element2);
						} else {
							flag = false;
						}
				     }
				}
			}
			return document;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("XzzfAction 中 checkItemInit()方法："+e.getMessage());
		}
		return null;
	}
	


	public boolean hasPermissionByFunCode(TbUser user, String module, int permissionVaule) throws Exception {
		return hasPermission(user, this.getFunByCode(module), permissionVaule);
	}
	
	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public boolean hasPermission(TbUser user, TbSysFun fun, int permission) throws Exception{
		String grade = user.getTbUserGrade().getId().toString();
		if("0".equals(grade) || "1".equals(grade)){
			return true;
		}
		List list = (List)this.utilDao.getHqlQuery("from TbUserRoleFun t where 1=1 and t.roleId="+user.getTbUserRole().getId()+" and t.funId="+fun.getId()+"");
		if(null!=list && list.size()>0){
			TbUserRoleFun roleFun = (TbUserRoleFun)list.get(0);
			return roleFun.getPermission(permission) == 1;
		}
		return false;
	}
	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public boolean hasPermissionByRole(TbUserRole role,TbSysFun fun, int permission) throws Exception{//根据角色和权限id判断，该权限是否有该权限的子权限
		List list = (List)this.utilDao.getHqlQuery("from TbUserRoleFun t where 1=1 and t.roleId="+role.getId()+" and t.funId="+fun.getId()+"");
		if(null!=list && list.size()>0){
			TbUserRoleFun roleFun = (TbUserRoleFun)list.get(0);
			return roleFun.getPermission(permission) == 1;
		}
		return false;
	}

	public List getFunListByRole(TbUserRole role) throws Exception {
		return (List)this.utilDao.getHqlQuery("from TbSysFun t where 1=1 and exists(from TbUserRoleFun f where t.id=f.funId and f.roleId="+role.getId()+") order by t.funParentId,t.funSort");
	}

/*	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List getDeptList(String cType, String deptCode) throws Exception {
		try {
			List list = null;
			TbUserDept sysDept = this.getDeptByCode(Util.DEPT_CODE);
			if(Constants.DEPT_TYPE_ID_OF_OFFICE.equals(cType)){//科室
				list = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and (t.deptType=1 or t.deptParentId="+sysDept.getId()+") and t.isDele=0 order by t.id");
				if(null!=list && list.size()>0){
					for(int i=0;i<list.size();i++){
						TbUserDept dept = (TbUserDept)list.get(i);
						if(Constants.DEPT_GRADE_CITY.equals(dept.getDeptGrade()) && Constants.DEPT_TYPE_ID_OF_OFFICE.equals(dept.getDeptType()) 
								&& Constants.DEPT_CLASS_SAFETY_BUREAU.equals(dept.getDeptClass())){//如果是市安监局
							dept.setDeptParentId(1L);
						}
						if(Constants.DEPT_GRADE_COUNTRY.equals(dept.getDeptGrade()) && 
								Constants.DEPT_CLASS_SAFETY_BUREAU.equals(dept.getDeptClass())){//县(市、区)、开发区
							dept.setDeptParentId(2L);
							dept.setDeptName(dept.getDeptName());
							dept.setDeptGrade("3");
						}
					}
				}
			}else if(Constants.DEPT_TYPE_ID_OF_INDUSTRY.equals(cType)){//行业
				list = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and (t.deptType=2 or t.deptParentId="+sysDept.getId()+") and t.isDele=0 order by t.id");
				if(null!=list && list.size()>0){
					for(int i=0;i<list.size();i++){
						TbUserDept dept = (TbUserDept)list.get(i);
						if(Constants.DEPT_GRADE_CITY.equals(dept.getDeptGrade()) && Constants.DEPT_TYPE_ID_OF_INDUSTRY.equals(dept.getDeptType())){//如果是市行业
							dept.setDeptParentId(Long.parseLong("1"));
						}
						if(sysDept.getId().toString().equals(dept.getDeptParentId().toString()) && Constants.DEPT_TYPE_ID_OF_DISTRICT.equals(dept.getDeptType())){//县(市、区)、开发区
							dept.setDeptParentId(Long.parseLong("2"));
							dept.setDeptGrade("3");
						}
					}
				}
			}else if("3".equals(cType)){//属地
				List alllist = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.deptType=3 and t.isDele=0 order by t.id");
				List<TbUserDept> tempList = new ArrayList<TbUserDept>();
				list = this.getAllChildDepts(sysDept, alllist, tempList);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}*/
	
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List getDeptList(String cType, String deptCode) throws Exception {
		try {
			List list = null;
			TbUserDept sysDept = this.getDeptByCode(Util.DEPT_CODE);
			if(Constants.DEPT_TYPE_ID_OF_OFFICE.equals(cType)){//科室
				list = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and (t.deptType=1 or t.deptParentId="+sysDept.getId()+") and t.isDele=0 order by t.id");
				if(null!=list && list.size()>0){
					for(int i=0;i<list.size();i++){
						TbUserDept dept = (TbUserDept)list.get(i);
						if("2".equals(dept.getDeptGrade()) && "1".equals(dept.getDeptType()) && "1".equals(dept.getDeptClass())){//如果是市安监局
							dept.setDeptParentId(Long.parseLong("1"));
						}
						if(sysDept.getId().toString().equals(dept.getDeptParentId().toString()) && "3".equals(dept.getDeptType())){//县(市、区)、开发区
							dept.setDeptParentId(Long.parseLong("2"));
							dept.setDeptName(dept.getDeptName()+"安监局");
							dept.setDeptGrade("3");
						}
					}
				}
			}else if("2".equals(cType)){//行业
				list = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and (t.deptType=2 or t.deptParentId="+sysDept.getId()+") and t.isDele=0 order by t.id");
				if(null!=list && list.size()>0){
					for(int i=0;i<list.size();i++){
						TbUserDept dept = (TbUserDept)list.get(i);
						if("2".equals(dept.getDeptGrade()) && "2".equals(dept.getDeptType())){//如果是市行业
							dept.setDeptParentId(Long.parseLong("1"));
						}
						if(sysDept.getId().toString().equals(dept.getDeptParentId().toString()) && "3".equals(dept.getDeptType())){//县(市、区)、开发区
							dept.setDeptParentId(Long.parseLong("2"));
							dept.setDeptGrade("3");
						}
					}
				}
			}else if("3".equals(cType)){//属地
				List alllist = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.deptType=3 and t.isDele=0 order by t.id");
				List<TbUserDept> tempList = new ArrayList<TbUserDept>();
				list = this.getAllChildDepts(sysDept, alllist, tempList);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 查找某一节点下所有子菜单
	 */
	public List<TbUserDept> getAllChildDepts(TbUserDept dept,List<TbUserDept> allList,List<TbUserDept> tempList)throws Exception {
		try {
			List<TbUserDept> list = null;
			if(dept != null && allList != null && allList.size() > 0){
				list = this.findChildDepts(dept, allList);
				if(list != null && list.size() > 0){
					for(TbUserDept fun1 : list){
						tempList.add(fun1);
						this.getAllChildDepts(fun1, allList, tempList);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("查找某一节点下所有子菜单:List<TbUserDept> getAllChildDepts(TbUserDept dept,List<TbUserDept> allList,List<TbUserDept> tempList):"+e);
		}
		return tempList;
	}
	
	 /**
     * 查找某节点下所有属地部门
     * @param dept
     * @param allList所有菜单
     * @return
     * @throws Exception
     */
	public List<TbUserDept> findChildDepts(TbUserDept dept,List<TbUserDept> allList)throws Exception{
		List<TbUserDept> childNods = new ArrayList<TbUserDept>();
		try {
			if(allList != null && allList.size() > 0){
				for(TbUserDept dept1 : allList){
					if(null!=dept1.getDeptParentId() && dept.getId().toString().equals(dept1.getDeptParentId().toString())){
						childNods.add(dept1);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("查找某节点子菜单:List<TbUserDept> findChildDepts(TbUserDept fun,List<TbUserDept> allList):"+e.getMessage());
		}
		return childNods;
	}

	public TbUserDept getDeptByCode(String deptCode) throws Exception {
		List list = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.deptCode='"+deptCode+"'");
		if(null!=list && list.size()>0){
			return (TbUserDept)list.get(0);
		}
		return null;
	}

	public List getAllDeptList() throws Exception {
		List list = new ArrayList();
		List sdList = this.getDeptList("3", Util.DEPT_CODE);
		List kshy = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.isDele=0 and t.deptType in(0,1,2)");
		list.addAll(sdList);
		list.addAll(kshy);
		return list;
	}

	public List getUserList(String hql, int start, int count) throws Exception {
		StringBuffer hqls = new StringBuffer();
		if(count == 0){
			hqls.append("select count(*) from TbUserView t ").append(hql);
		}else{
			hqls.append("from TbUserView t ").append(hql);
		}
		return (List)this.utilDao.getHqlQuery(hqls.toString(), start, count);
	}

	public List getUserGradeList() throws Exception {
		return (List)this.utilDao.getHqlQuery("from TbUserGrade t where 1=1 and t.isDele=0 and t.id not in(0,1) order by t.id");
	}

	public List getCorpTypeList() throws Exception {
		return (List)this.utilDao.getHqlQuery("from TbCorpType t where 1=1 and t.isDele=0 order by t.id");
	}
	
	public List getDeptMainList()throws Exception{
		List list = new ArrayList();
		List allDeptList = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.deptGrade=2 and (t.deptType=1 or t.deptType=2) order by t.deptType,t.id");
		for(int i=0;i<allDeptList.size();i++){
			TbUserDept dept = (TbUserDept)allDeptList.get(i);
			if("1".equals(dept.getDeptType()) && "3".equals(dept.getDeptClass()) && "2".equals(dept.getDeptGrade())){
				dept.setDeptName("安监局-"+dept.getDeptName());
				list.add(dept);
			}
			if("2".equals(dept.getDeptType()) && "2".equals(dept.getDeptGrade())){
				list.add(dept);
			}
		}
		return list;
	}

	public List getMaxTypeList() throws Exception {
		return (List)this.utilDao.getHqlQuery("from TbCorpType t where 1=1 and t.typeParentId=0 and t.isDele=0 order by t.id");
	}

	public List getQuDeptList() throws Exception {
		TbUserDept dept = this.getDeptByCode(Util.DEPT_CODE);
		return (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.deptParentId="+dept.getId()+" and t.deptType=3 and t.isDele=0 order by t.id");
	}

	public TbUser existsUserName(String userId, String userName)throws Exception {
		try {
			StringBuilder hql = new StringBuilder("from TbUser t where 1=1 and t.isDele=0 and t.userName='"+userName.trim()+"'");
			if(null!=userId && userId.length()>0){
				hql.append(" and t.id != "+userId+"");
			}
			List list = (List)this.utilDao.getHqlQuery(hql.toString());
			if(null!=list && list.size()>0){
				return (TbUser)list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("SystemServiceImpl:TbUser existsUserName(String userId, String userName)异常："+e.getMessage());
		}
		return null;
	}

	public List getChildDeptList(TbUserDept dept) throws Exception {
		List alllist = (List)this.utilDao.getHqlQuery("from TbUserDept t where 1=1 and t.isDele=0 order by t.id");
		List<TbUserDept> tempList = new ArrayList<TbUserDept>();
		List list = this.getAllChildDepts(dept, alllist, tempList);
		return list;
	}
	
	public void addOrUpdateInitDatas(String xmlFilePath) {
		try {
			Document document = new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFilePath));
			List parents = document.selectNodes("//Districts/District");
			for(int i=0; i < parents.size(); i++) {
				Element element = (Element) parents.get(i);
				TbUserDept ppp = new TbUserDept();
				ppp.setDeptCode(element.attributeValue("code"));
				ppp.setDeptName(element.attributeValue("name"));
				ppp.setId(this.getUserDeptIdByUserDeptName(ppp.getDeptName()));
				this.importDistricts(element.selectNodes("District") ,ppp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	public void importDistricts(List<Element> districts, TbUserDept parent) throws Exception {
		for (Iterator<Element> iter = districts.iterator(); iter.hasNext();) {
			Element element = (Element) iter.next();
			TbUserDept dis = new TbUserDept();
			dis.setDeptCode(element.attributeValue("code"));
			dis.setDeptName(element.attributeValue("name"));
			dis.setDeptType("3");
			dis.setIsDele("0");
			dis.setDeptParentName(parent.getDeptName());
			dis.setDeptParentId(parent.getId());
			/*if(parent!=null){
				dis.setDeptParentName(parent.getDeptName());
				dis.setDeptParentId(this.getUserDeptIdByUserDeptName(parent.getDeptName()));
			}*/
			this.utilDao.saveOrUpdate(dis);
			importDistricts(element.selectNodes("District"), dis);
		}
	}
}
